package org.haredot.service.impl;

import org.haredot.dto.TreeNode;
import org.haredot.entity.Role;
import org.haredot.mapper.RoleMapper;
import org.haredot.service.RoleService;
import org.haredot.vo.ResultVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper ;

    @Override
    public ResultVo<?> saveRole(Role role) {
        // 根据角色名、查询该角色是否已经被存储
        Role r = roleMapper.findRoleByName(role.getName());

        if (r !=null) {
            return ResultVo.fail("角色名已存在").build();
        }
        // 根据 角色 标识符 查询该角色是否存在
        r = roleMapper.findRoleByRemark(role.getRemark());

        if (r != null) {
            return ResultVo.fail("角色标识符已存在").build();
        }
        // 存储角色
        roleMapper.insert(role) ;

        return ResultVo.ok().build();
    }

    @Override
    public ResultVo<?> modifyRole(Role role) {
        // 查询 修改的角色名是否重复
        Role r = roleMapper.findRoleByName(role.getName());
        if (r !=null && !Objects.equals(r.getId(), role.getId())) {
            return ResultVo.fail("角色名已存在").build();
        }

        r = roleMapper.findRoleByRemark(role.getRemark());

        if (r !=null && !Objects.equals(r.getId(), role.getId())) {
            return ResultVo.fail("角色标记名已存在").build();
        }
        // 修改数据
        roleMapper.updateByPrimaryKey(role) ;

        return ResultVo.ok().build();
    }

    @Override
    public ResultVo<?> removeRole(Long roleId) {
        // 判断是否是超级管理员 (内置账户 built ，默认为 1)
        Role role = roleMapper.selectByPrimaryKey(roleId);
        if (role.isBuilt()) {
            return ResultVo.fail("内置角色、禁止删除").build();
        }

        int len = roleMapper.deleteByPrimaryKey(roleId);

        return ResultVo.asserts(len ==1 , "数据删除失败").build();
    }

    @Override
    public ResultVo<?> queryRoles() {
        List<Role> roles = roleMapper.findAll();
        return ResultVo.ok().data(roles).build();
    }

    @Override
    public ResultVo<?> queryTreeNodes(Long roleId) {
        List<TreeNode> treeByRoleId = roleMapper.findTreeByRoleId(roleId);
        return ResultVo.ok().data(treeByRoleId).build();
    }

    @Override
    public ResultVo<?> bindPermission(Long roleId, List<String> nodes) {
        // 删除 角色 原有的 权限
        roleMapper.removePermissionByRoleId(roleId) ;

        // 添加新的权限
        if (!nodes.isEmpty()) {
            roleMapper.batchInsertPermission(roleId, nodes);
        }
        return ResultVo.ok().build();
    }
}
